#include "test.h"

#include <QDebug>
#include <QTimer>

#include "System.h"
#include "TaskStateMachine.h"  // 需要常量定义
#include "ui_test.h"

test::test(QWidget* parent) : QWidget(parent), ui(new Ui::test)
{
    ui->setupUi(this);

    // 获取System实例
    m_system = System::instance();

    // 连接信号
    connect(m_system, &System::currentTaskChanged, this, &test::onCurrentTaskChanged);
    connect(m_system, &System::isRunningChanged, this, &test::onSystemRunningChanged);

    // 设置UI
    setupUI();

    // 启动状态更新定时器
    QTimer* statusTimer = new QTimer(this);
    connect(statusTimer, &QTimer::timeout, this, &test::updateStatus);
    statusTimer->start(500);  // 每500ms更新一次状态
}

test::~test() { delete ui; }

void test::setupUI()
{
    // 直接在现有的ui布局中添加控件
    createAtomicOperationButtons();
    createCompositeTaskButtons();
    createStatusDisplay();
    createControlButtons();

    setWindowTitle("System 测试页面");
    resize(1000, 800);
}

void test::createAtomicOperationButtons()
{
    m_atomicGroupBox = new QGroupBox("原子操作", this);
    m_atomicGroupBox->setMinimumHeight(200);
    QGridLayout* layout = new QGridLayout(m_atomicGroupBox);
    layout->setSpacing(8);
    layout->setContentsMargins(10, 10, 10, 10);

    // 存储所有按钮
    m_atomicButtons.clear();

    // 遍历所有原子操作创建按钮
    for (int i = 0; i <= static_cast<int>(AtomicOperation::STOP_DEVICE); ++i) {
        qint16 operationCode = static_cast<qint16>(i);
        QString operationName = m_system->getTaskName(operationCode);

        QPushButton* button = new QPushButton(operationName, this);
        button->setMinimumHeight(35);
        button->setMinimumWidth(120);
        m_atomicButtons[operationCode] = button;

        // 连接信号到统一的槽函数
        connect(button, &QPushButton::clicked, this,
                [this, operationCode]() { onAtomicOperationClicked(operationCode); });

        // 计算按钮在网格中的位置 (4列)
        int row = i / 4;
        int col = i % 4;
        layout->addWidget(button, row, col);
    }

    m_atomicGroupBox->setLayout(layout);
    ui->gridLayout->addWidget(m_atomicGroupBox, 0, 0);  // 添加到现有布局
}

void test::createCompositeTaskButtons()
{
    m_compositeGroupBox = new QGroupBox("复合任务", this);
    m_compositeGroupBox->setMinimumHeight(80);
    QHBoxLayout* layout = new QHBoxLayout(m_compositeGroupBox);
    layout->setSpacing(15);
    layout->setContentsMargins(10, 10, 10, 10);

    // 创建按钮
    m_btnCompositeAnalysis = new QPushButton("水样测量任务", this);
    m_btnCompositeSpikeRecovery = new QPushButton("加标回收任务", this);

    // 设置按钮尺寸和样式
    m_btnCompositeAnalysis->setMinimumHeight(40);
    m_btnCompositeAnalysis->setMinimumWidth(150);
    m_btnCompositeSpikeRecovery->setMinimumHeight(40);
    m_btnCompositeSpikeRecovery->setMinimumWidth(150);

    m_btnCompositeAnalysis->setStyleSheet(
        "QPushButton { background-color: #4CAF50; color: white; font-weight: bold; padding: 10px; "
        "}");
    m_btnCompositeSpikeRecovery->setStyleSheet(
        "QPushButton { background-color: #2196F3; color: white; font-weight: bold; padding: 10px; "
        "}");

    // 连接信号
    connect(m_btnCompositeAnalysis, &QPushButton::clicked, this, &test::onCompositeAnalysisClicked);
    connect(m_btnCompositeSpikeRecovery, &QPushButton::clicked, this,
            &test::onCompositeSpikeRecoveryClicked);

    layout->addWidget(m_btnCompositeAnalysis);
    layout->addWidget(m_btnCompositeSpikeRecovery);
    layout->addStretch();

    m_compositeGroupBox->setLayout(layout);
    ui->gridLayout->addWidget(m_compositeGroupBox, 1, 0);  // 添加到现有布局
}

void test::createStatusDisplay()
{
    m_statusGroupBox = new QGroupBox("状态信息", this);
    m_statusGroupBox->setMinimumHeight(200);
    QVBoxLayout* layout = new QVBoxLayout(m_statusGroupBox);
    layout->setSpacing(5);
    layout->setContentsMargins(10, 10, 10, 10);

    // 创建状态标签
    m_lblCurrentTask = new QLabel("当前任务: 无", this);
    m_lblCurrentStep = new QLabel("当前步骤: 无", this);
    m_lblTotalSteps = new QLabel("总步骤数: 0", this);
    m_lblCurrentOperation = new QLabel("当前操作: 空闲", this);
    m_lblTaskStatus = new QLabel("任务状态: 空闲", this);

    // 设置标签样式和尺寸
    QString labelStyle =
        "QLabel { font-size: 12px; padding: 8px; border: 1px solid #ccc; background-color: "
        "#f9f9f9; }";
    m_lblCurrentTask->setStyleSheet(labelStyle);
    m_lblCurrentStep->setStyleSheet(labelStyle);
    m_lblTotalSteps->setStyleSheet(labelStyle);
    m_lblCurrentOperation->setStyleSheet(labelStyle);
    m_lblTaskStatus->setStyleSheet(labelStyle);

    // 设置标签最小高度
    m_lblCurrentTask->setMinimumHeight(30);
    m_lblCurrentStep->setMinimumHeight(30);
    m_lblTotalSteps->setMinimumHeight(30);
    m_lblCurrentOperation->setMinimumHeight(30);
    m_lblTaskStatus->setMinimumHeight(30);

    layout->addWidget(m_lblCurrentTask);
    layout->addWidget(m_lblCurrentStep);
    layout->addWidget(m_lblTotalSteps);
    layout->addWidget(m_lblCurrentOperation);
    layout->addWidget(m_lblTaskStatus);
    layout->addStretch();

    m_statusGroupBox->setLayout(layout);
    ui->gridLayout->addWidget(m_statusGroupBox, 2, 0);  // 添加到现有布局
}

void test::createControlButtons()
{
    m_controlGroupBox = new QGroupBox("控制操作", this);
    m_controlGroupBox->setMinimumHeight(80);
    QHBoxLayout* layout = new QHBoxLayout(m_controlGroupBox);
    layout->setSpacing(10);
    layout->setContentsMargins(10, 10, 10, 10);

    // 创建控制按钮
    m_btnStopCurrentTask = new QPushButton("停止当前任务", this);
    m_btnStopCurrentTask->setMinimumHeight(40);
    m_btnStopCurrentTask->setMinimumWidth(150);
    m_btnStopCurrentTask->setStyleSheet(
        "QPushButton { background-color: #f44336; color: white; font-weight: bold; padding: 10px; "
        "}");

    // 连接信号
    connect(m_btnStopCurrentTask, &QPushButton::clicked, this, &test::onStopCurrentTaskClicked);

    layout->addWidget(m_btnStopCurrentTask);
    layout->addStretch();

    m_controlGroupBox->setLayout(layout);
    ui->gridLayout->addWidget(m_controlGroupBox, 3, 0);  // 添加到现有布局
}

// 统一的原子操作槽函数
void test::onAtomicOperationClicked(qint16 operationCode)
{
    if (m_system) {
        m_system->execTask(operationCode);
    }
}

// 复合任务槽函数
void test::onCompositeAnalysisClicked()
{
    if (m_system) {
        m_system->execTask(COMPOSITE_TASK_ANALYSIS);  // 水样测量任务
    }
}

void test::onCompositeSpikeRecoveryClicked()
{
    if (m_system) {
        m_system->execTask(COMPOSITE_TASK_SPIKE_RECOVERY);  // 加标回收任务
    }
}

// 系统状态槽函数
void test::onCurrentTaskChanged(qint16 operateCode)
{
    m_currentTaskCode = operateCode;
    qDebug() << "当前任务变化:" << operateCode << m_system->getTaskName(operateCode);
}

void test::onSystemRunningChanged(bool isRunning) { qDebug() << "系统运行状态变化:" << isRunning; }

// 控制按钮槽函数
void test::onStopCurrentTaskClicked()
{
    if (m_system) {
        m_system->stop();
    }
}

// 状态更新
void test::updateStatus()
{
    if (!m_system) return;

    // 更新状态显示
    QString taskName = m_system->getTaskName(m_currentTaskCode);
    m_lblCurrentTask->setText(QString("当前任务: %1").arg(taskName.isEmpty() ? "无" : taskName));

    // 简化的状态显示（System接口相对简单）
    m_lblCurrentStep->setText("当前步骤: N/A");
    m_lblTotalSteps->setText("总步骤数: N/A");
    m_lblCurrentOperation->setText(
        QString("当前操作: %1").arg(m_currentTaskCode == 0 ? "空闲" : taskName));

    QString status = m_system->isRunning() ? "运行中" : "空闲";
    m_lblTaskStatus->setText(QString("系统状态: %1").arg(status));
}